#coding=utf8
import os
import re
from util.configer_generator import configer

class Server:
    def __init__(self,p_server_name):
        self.p_server_name=p_server_name
        self.device_port_dic={}
        self.device_Port_Dic()

   # appium - p 4700 - bp 4701 - U 127.0.0.1: 51244 - -no - reset - -session - override
   #  netstat - ano | findstr 4723　查看端口号是否被占用
   #  taskkill - f - pid node.exe关闭appium进程
    def kill_Server(self):#关闭appium服务器
        commd_str="taskkill -f -pid %s"%self.p_server_name#杀掉进程dos命令
        if  "PID" in os.popen(commd_str).read():
            return True
        else:
            return False

    def usable_Port_Generator(self,port):
        commd_str="netstat -ano | findstr %s"%port
        temp=os.popen(commd_str).read()
        if  temp=="":
            return port
        else:
            return None

    def device_Port(self):
        self.devices_list=Server.find_Devices()
        temp_port_list=[]
        if self.devices_list!=None:
            num_ports=len(self.devices_list)*2
            port=configer.get_int("appium","port_source")#从配置文件中读取
            for j in range(num_ports):
                useif = self.usable_Port_Generator(port)
                for i in range(1, 101):
                    if useif==None:
                        useif=self.usable_Port_Generator(port+i)
                    else:
                        temp_port_list.append(useif)
                        port = useif + 1
                        break
                else:
                    return None
            else:
                return temp_port_list



    def device_Port_Dic(self):
        port_list=self.device_Port()
        devices=self.devices_list
        if devices:
            num_devices=len(devices)
            if port_list!=None:
                for i in range(num_devices):
                    self.device_port_dic[devices[i]]=port_list[2*i:2*i+2]
            else:
                return None
        else:
            return None





    def start_Server(self,p_port,bp_port,device_name):#启动appium server
            commd_str="appium -a 0.0.0.0 -p %s -pa /wd/hub/"%(p_port)
            os.system(commd_str)#需判断服务器是否启动成功
            print(commd_str)
            return commd_str

    @staticmethod
    def find_Devices():#返回当前已经连接的设备的deviceName
        list=[]
        list_temp = []
        commd_str=configer.get_str("devices","find_Devices")#查看当前设备的adb命令
        temp1=os.popen(commd_str)
        while(True):
            temp2=temp1.readline()
            if temp2=="":
                break
            list.append(temp2)
        list.pop(0)#删除列表第一个元素
        list.pop()#删除""空字符串
        for i in list:
            is_device=i.strip().split("\t")
            if is_device[1]=="device":
                list_temp.append(is_device[0])
        if len(list_temp)==0:
            return None
        else:
            return list_temp




if __name__=="__main__":
    server=Server("node.exe")
    print(server.devices_list)

